package org.farm.product.domain.chain;

import org.farm.product.domain.bo.ProductSpuBo;
import org.farm.product.domain.chain.handler.ProductSpuHandler;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2025/4/22
 * @description
 */
@Component
public class ProductSpuChainBuilder {

    private final List<ProductSpuHandler> handlers;

    public ProductSpuChainBuilder(List<ProductSpuHandler> handlers) {
        // 按照注解的顺序排序
        this.handlers = handlers.stream().sorted(AnnotationAwareOrderComparator.INSTANCE).collect(Collectors.toList());
        // 批量设置下一个处理器
        for (int i = 0; i < handlers.size() - 1; i++) {
            handlers.get(i).setNextHandler(handlers.get(i + 1));
        }
    }

    /**
     * 外部调用入口
     * @param productSpuBo 商品spu信息
     */
    public void process(ProductSpuBo productSpuBo) {
        if (!CollectionUtils.isEmpty(handlers)) {
            handlers.get(0).handler(productSpuBo);
        }
    }
}
